﻿///***************************************************************
/// 시  스  템 : Updms.Mny
/// 단위시스템 : MNY
/// 계      층 : Presentation Layer
/// 프로그램명 : Mny1011m
/// 파  일  명 : Mny1011m.aspx.cs
/// 설      명 : 현금출납관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-08-04 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Mny.Exe;

namespace Updms.Mny
{
	public partial class Mny1011m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Mny1011m";
		public static readonly string gs_path_info = "/updms/Mny/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Mny mny = new CommCode.Mny(LANG_SET);

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = GRID_PAGESIZE;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	//날짜시작일
		protected string kw2 = "";	//날짜종료일
		protected string kw3 = "";	//구분
		protected string kw4 = "";	//계정
		protected string kw5 = "";	//내용

		//메뉴 선택값
		protected string gs_sm = "";

		//합계
		decimal ld_amount = 0;

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SelectProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetClass();
			SetSearchAccount();
			SetAccount();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			//onKeyUp이벤트
			txt_amount.Attributes.Add("onkeyup", "$(\"txt_amount\").value=addComma($(\"txt_amount\").value);");

			//엔터검색
			txt_search_reg_dt_from.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_reg_dt_to.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_contents.Attributes.Add("onkeypress", "enterSearchOnPage(event)");

			//달력콘트롤 설정
			ce_reg_dt.SelectedDate = DateTime.Now.AddDays(0);
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))
					{
						if (String.IsNullOrEmpty(txt_search_reg_dt_from.Text))
						{
							kw1 = DateUtil.GetMonthEx(-3, "yyyy-MM") + "-01";	//오늘부터 3개월전
							txt_search_reg_dt_from.Text = kw1;
						}
						else
						{
							kw1 = txt_search_reg_dt_from.Text.Trim();
						}
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						txt_search_reg_dt_from.Text = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))
					{
						if (String.IsNullOrEmpty(txt_search_reg_dt_to.Text))
						{
							kw2 = DateUtil.GetLastMonthDay(DateUtil.GetMonthEx(0, "yyyy-MM")); //당월의 마지막일
							txt_search_reg_dt_to.Text = kw2;
						}
						else
						{
							kw2 = txt_search_reg_dt_to.Text.Trim();
						}
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						txt_search_reg_dt_to.Text = kw2;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))
					{
						kw3 = ddl_search_class.SelectedValue;
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						ddl_search_class.SelectedValue = kw3;
					}
					SetSearchAccount();

					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))
					{
						kw4 = ddl_search_account.SelectedValue;
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						ddl_search_account.SelectedValue = kw4;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw5"]))
					{
						kw5 = txt_search_contents.Text.Trim();
					}
					else
					{
						kw5 = Server.UrlDecode(Request.QueryString["kw5"]);
						txt_search_contents.Text = kw5;
					}
					break;
				case "SEARCH":
					kw1 = String.IsNullOrEmpty(txt_search_reg_dt_from.Text) ? DateUtil.GetMonthEx(-3, "yyyy-MM")+"-01" : txt_search_reg_dt_from.Text.Trim();
					kw2 = String.IsNullOrEmpty(txt_search_reg_dt_to.Text) ? DateUtil.GetLastMonthDay(DateUtil.GetMonthEx(0, "yyyy-MM")) : txt_search_reg_dt_to.Text.Trim();
					kw3 = ddl_search_class.SelectedValue;
					kw4 = ddl_search_account.SelectedValue;
					kw5 = txt_search_contents.Text.Trim();
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw3 = ConversionUtil.CompareReplace(ddl_search_class.SelectedItem.Text, DDL_SELECT, "-");
			string ls_kw4 = ConversionUtil.CompareReplace(ddl_search_account.SelectedItem.Text, DDL_SELECT, "-");			

			lbl_search_keyword.Text = kw1 + " ~ " +kw2+ " / " + ls_kw3 + " / " + ls_kw4 + " / " + kw5;
		}

		#endregion

		#region 마스터 Method (SetClass, SetSearchAccount)

		//구분
		private void SetClass()
		{
			mny.SetClass(ddl_search_class);
			mny.SetClass(ddl_class);

			ddl_search_class.Items.Insert(0, new ListItem(DDL_SELECT, ""));
			ddl_class.Items.Insert(0, new ListItem(DDL_SELECT, ""));
		}

		//계정
		private void SetSearchAccount()
		{
			string ls_ucd = "";  // AA001:수입, AA002:저축, AA003:지출 
			DataSet lo_ds = new DataSet();
			ddl_search_account.Items.Clear();
			
			if (ddl_search_class.SelectedIndex == 0)
			{
				ddl_search_account.Items.Insert(0, new ListItem(DDL_SELECT, ""));
			}
			else
			{
				ls_ucd = ddl_search_class.SelectedValue;
				lo_ds.Merge(global.GetCommUCd("MNY", ls_ucd, LANG_SET, DDL_SELECT));

				ddl_search_account.DataSource = lo_ds;
				ddl_search_account.DataMember = "UPDMS_COM_CD";
				ddl_search_account.DataTextField = "Text";
				ddl_search_account.DataValueField = "Value";
				ddl_search_account.DataBind();
			}
		}

		protected void ddl_search_class_SelectedIndexChanged(object sender, EventArgs e)
		{
			SetSearchAccount();
		}

		#endregion

		#region 디테일 Method (SetAccount)

		//계정
		private void SetAccount()
		{
			string ls_ucd = ""; 
			DataSet lo_ds = new DataSet();
			ddl_account.Items.Clear();

			if (ddl_class.SelectedIndex == 0)
			{
				ddl_account.Items.Insert(0, new ListItem(DDL_SELECT, ""));
			}
			else
			{
				ls_ucd = ddl_class.SelectedValue;
				lo_ds.Merge(global.GetCommUCd("MNY", ls_ucd, LANG_SET, ""));

				ddl_account.DataSource = lo_ds;
				ddl_account.DataMember = "UPDMS_COM_CD";
				ddl_account.DataTextField = "Text";
				ddl_account.DataValueField = "Value";
				ddl_account.DataBind();
			}
		}

		protected void ddl_class_SelectedIndexChanged(object sender, EventArgs e)
		{
			SetAccount();
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;

			//검색
			lo_dp.AddProperty("ls_reg_dt_from", typeof(string), kw1);
			lo_dp.AddProperty("ls_reg_dt_to", typeof(string), kw2);
			lo_dp.AddProperty("ls_class", typeof(string), kw3);
			lo_dp.AddProperty("ls_account", typeof(string), kw4);
			lo_dp.AddProperty("ls_contents", typeof(string), kw5);

			using (Mny1011m_NT _Mny1011m_NT = new Mny1011m_NT())
			{
				li_row_count = _Mny1011m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
				lbl_page.Visible = !cb_list_all.Checked;		

				lo_ds.Merge(_Mny1011m_NT.SelectProcess(lo_dp));

				GridView1.DataSource = lo_ds;
				GridView1.DataBind();

				string search_condition = "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&kw4=" + Server.UrlEncode(kw4) + "&kw5=" + Server.UrlEncode(kw5) + "&page=";

				Pager pager = new Pager(this, ref lbl_page);
				pager.PageNavigation(
					li_cur_page,
					li_page_count,
					gs_path_info + search_condition);

				//결과출력(키워드, 검색행수)
				ShowKeywordLabel();
				lbl_result_count.Text = li_row_count.ToString("#,###,##0");

				//즐겨찾기
				ibtn_favorite.Attributes.Add("onclick", "javascript:goFavoriteSearchPage('" + PID + "','" + search_condition + "');return false;");
			}
		}

		//저장
		private void InsertProcess()
		{
			using (Mny1011m_RT _Mny1011m_RT = new Mny1011m_RT())
			{
				int li_return = _Mny1011m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Mny1011m_RT _Mny1011m_RT = new Mny1011m_RT())
			{
				int li_return = _Mny1011m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Mny1011m_RT _Mny1011m_RT = new Mny1011m_RT())
			{
				int li_return = _Mny1011m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";	//삭제되었습니다:삭제할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
		}

		#endregion

		#region SetValue, ClearValue

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("Seq",			typeof(string),		lbl_pk.Text);
			lo_dp.AddProperty("Reg_Dt",			typeof(string), 	ConversionUtil.DefaultValue(txt_reg_dt.Text));
			lo_dp.AddProperty("Class",			typeof(string), 	ddl_class.SelectedValue);
			lo_dp.AddProperty("Account",		typeof(string), 	ddl_account.SelectedValue);
			lo_dp.AddProperty("Contents",		typeof(string), 	ConversionUtil.DefaultValue(txt_contents.Text));
			lo_dp.AddProperty("Amount",			typeof(string), 	ConversionUtil.ExtractNumberStr(txt_amount.Text));
			lo_dp.AddProperty("Remark",			typeof(string), 	ConversionUtil.DefaultValue(txt_remark.Text));
			lo_dp.AddProperty("Create_User",	typeof(string), 	USER_ID);
			lo_dp.AddProperty("Create_Dt",		typeof(string), 	"");
			lo_dp.AddProperty("Update_User",	typeof(string), 	USER_ID);
			lo_dp.AddProperty("Update_Dt",		typeof(string), 	"");
			
			return lo_dp;
		}

		//ClearValue
		private void ClearValue()
		{
			lbl_pk.Text = "";
			h_no.Value = "";
			ce_reg_dt.SelectedDate = DateTime.Now.AddDays(0);
			ddl_class.SelectedIndex = 0;
			SetAccount();
			txt_contents.Text = "";
			txt_amount.Text = "";
			txt_remark.Text = "";
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			//페이지모드 처리
			string ls_class = String.IsNullOrEmpty(lbl_pk.Text) ? "sbtn sbtn_mode_i" : "sbtn sbtn_mode_u";
			string ls_title = String.IsNullOrEmpty(lbl_pk.Text) ? "입력" : "수정";
			btn_chg_mode.Attributes.Add("class", ls_class);
			btn_chg_mode.Attributes.Add("title", ls_title);

			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text	= cb_list_all.Checked
					? (li_row_count - e.Row.RowIndex).ToString() 
					: ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();

				switch (GridView1.DataKeys[e.Row.RowIndex].Values["Class"].ToString())
				{
					case "AA001"://수입
						e.Row.Cells[6].Attributes.Add("class", "color_blue");
						break;
					case "AA002"://지출
						e.Row.Cells[6].Attributes.Add("class", "color_darkred");
						break;
					case "AA003"://저축
						e.Row.Cells[6].Attributes.Add("class", "color_darkgreen");
						break;
					default:
						e.Row.Cells[6].Attributes.Add("class", "color_darkred");
						break;
				}

				//합계
				ld_amount += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"));
			}

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer && ddl_search_class.SelectedIndex != 0)
			{
				GridView1.ShowFooter = true;
				e.Row.Cells[0].Text = "Total";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[0].ColumnSpan = 7;
				e.Row.Cells[1].Visible = false;
				e.Row.Cells[2].Visible = false;
				e.Row.Cells[3].Visible = false;
				e.Row.Cells[4].Visible = false;
				e.Row.Cells[5].Visible = false;
				e.Row.Cells[6].Visible = false;
				e.Row.Cells[7].Visible = false;
				e.Row.Cells[8].Visible = false;
				e.Row.Cells[9].Visible = false;
				e.Row.Cells[10].Text = ld_amount.ToString("#,###,##0");
				e.Row.Cells[10].Attributes.Add("class", "money");
				e.Row.Cells[11].Attributes.Add("class", "total");
			}
			else
			{
				GridView1.ShowFooter = false;
			}

			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView1);
			sGv.RowSpanGridView(GridView1, 3);//3.Base_Ym
			sGv.RowSpanGridView(GridView1, 6);//6.Class_Nm
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			//row.Cells[0].Text.ToString();//0.체크박스
			h_no.Value					= row.Cells[1].Text.ToString();								//1.번호
			lbl_pk.Text					= gv.DataKeys[row.RowIndex].Values["Seq"].ToString();		//2.Seq
																									//3.Base_Ym
			txt_reg_dt.Text				= row.Cells[4].Text.Trim();									//4.Reg_Dt
			ddl_class.SelectedValue		= gv.DataKeys[row.RowIndex].Values["Class"].ToString();		//5.Class
																									//6.Class_Nm
			SetAccount();
			ddl_account.SelectedValue	= gv.DataKeys[row.RowIndex].Values["Account"].ToString();	//7.Account
																									//8.Account_Nm
			txt_contents.Text			= lbtn_rc.Text;												//9.Comment (template)
			txt_amount.Text				= row.Cells[10].Text.Trim();								//10.Amount
			txt_remark.Text				= row.Cells[11].Text.Trim();								//11.Remark
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			if (global.CheckSaveMode("UPDMS_MNY_IN_OUT_MGT", "Seq", lbl_pk.Text.Trim()))
			{
				UpdateProcess();
			}
			else
			{
				InsertProcess();
			}
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
					sb.Append("<UPDMS_MNY_IN_OUT_MGT>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("</UPDMS_MNY_IN_OUT_MGT>");
				}
			}
			sb.Append("</UPDMS>");

			DeleteProcess(sb.ToString());
		}

		//차감
		protected void ibtn_balance_Click(object sender, EventArgs e)
		{
			string ls_seq = "";
			
			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					ls_seq += GridView1.DataKeys[i].Values["Seq"].ToString() + ",";
				}
			}
			//1,2,3, -> 1,2,3
			ls_seq = (ls_seq.Length > 0) ? ls_seq.Remove(ls_seq.Length - 1, 1) : "";
			CallJavaScriptMethodInAjax("goMnyBalancePage('" + ls_seq + "');");
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_reg_dt_from", typeof(string), kw1);
			lo_dp.AddProperty("ls_reg_dt_to", typeof(string), kw2);
			lo_dp.AddProperty("ls_class", typeof(string), kw3);
			lo_dp.AddProperty("ls_account", typeof(string), kw4);
			lo_dp.AddProperty("ls_contents", typeof(string), kw5);

			using (Mny1011m_NT _Mny1011m_NT = new Mny1011m_NT())
			{
				li_row_count = _Mny1011m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);				

				lo_ds.Merge(_Mny1011m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//디테일 초기화
		protected void lbtn_init_detail_Click(object sender, EventArgs e)
		{
			ClearValue();
		}

		//페이지모드변경
		protected void lbtn_chg_mode_Click(object sender, EventArgs e)
		{
			h_no.Value = "";
			lbl_pk.Text = "";
		}


		#endregion
		
	}
}
